package com.icesoft.core.web.helper;

import com.icesoft.core.common.helper.Resp;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletResponse;
import java.io.*;

@Slf4j
public abstract class ResponseUtils {

    public static void writeJson(HttpServletResponse response, Resp<?> resp) {
        response.setCharacterEncoding("utf8");
        response.setContentType("application/json");
        writeValue(response, resp.toJson());
    }

    public static void writeValue(HttpServletResponse response, String value) {
        response.setCharacterEncoding("utf8");
        try {
            PrintWriter out = response.getWriter();
            out.write(value);
            out.flush();
            out.close();
        } catch (IOException e) {
            log.error("writeValue error", e);
        }
    }

    /**
     * @param fileName 下载的自定义文件名
     */
    public static void writeToFileStream(HttpServletResponse response, String fileName, InputStream is)
            throws IOException {
        writeToFileStream(response, fileName, is, "application/octet-stream;charset=UTF-8");
    }

    public static void writeToFileStream(HttpServletResponse response, String fileName, InputStream is,
                                         String contentType) throws IOException {
        response.reset();
        response.setHeader("Content-Disposition",
                "attachment; filename=\"" + new String(fileName.getBytes(), "iso-8859-1") + "\"");
        response.setContentType(contentType);
        writeStream(response, is);
    }

    public static void writeStream(HttpServletResponse response, InputStream is)
            throws IOException {
        response.setCharacterEncoding("utf8");
        try (BufferedInputStream bis = new BufferedInputStream(is);
             OutputStream outputStream = new BufferedOutputStream(response.getOutputStream())) {
            byte[] buffer = new byte[1024];
            int i = bis.read(buffer);
            while (i != -1) {
                outputStream.write(buffer, 0, i);
                i = bis.read(buffer);
            }
            outputStream.flush();
            is.close();
        }
    }
}
